package com.heu.picture.controller;

import com.heu.picture.holder.UserHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

@RestController
@RequestMapping("/basic")
public class BasicController {


    @GetMapping("/hello")
    public String hello() {
        Long currentUserId = UserHolder.getCurrentUserId();
        System.out.println("hello _____");
        return "hello";
    }

    @GetMapping("/sse")
    public SseEmitter sse() {
        SseEmitter sseEmitter = new SseEmitter();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    sseEmitter.send(i);  // 发送数据
                    Thread.sleep(1000);   // 每秒发送一次
                }
            } catch (InterruptedException | IOException e) {
                sseEmitter.completeWithError(e);  // 发生异常时，关闭连接
            }
            sseEmitter.complete();  // 完成发送数据
        }).start();
        return sseEmitter;
    }
}
